<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

class PostsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth'); //没有登陆的用户无法访问这个页面
    }

    public function index(){   //用户登陆后显示所有他所关注的用的posts
        $users = auth()->user()->following()->pluck('profiles.user_id');
        $posts = Post::whereIn('user_id',$users)->with('user')->orderBy('created_at','DESC')->paginate(6);
        return view('posts.index',compact('posts'));
    }

    public function create()
    {
        return view('posts.create');
    }

    public function store()
    {
        $data = request()->validate([
            'caption'=>'required',
            'image'=>'required|image',
        ]);

        $imagePath = request('image')->store('uploads','public');

        $image = Image::make(public_path("storage/{$imagePath}"))->fit(1200,1200); //改变图像为正方形
        $image->save();
        auth()->user()->posts()->create([
            'caption'=>$data['caption'],
            'image'=>$imagePath,
        ]);//只有登陆后用户才能post

        


        return redirect('/profile/' . auth()->user()->id);
    }


    public function show(\App\Post $post)
    {
        return view('posts.show', compact('post')); //可以获取post所有内容
    }
}
